import daily.core.Person
import daily.securety.Account

class AccountController {

    def index() {

        def max = params.max ? params.max as int : 5
        def offset = params.offset ? params.offset as int : 0
        def order = params.order ? params.order as String : 'desc'
        def showAllPeople = params.showAllPeople ? params.showAllPeople as boolean : 'false'
        Person person = Person.findById(params.id);

        def accounts

        if (person) {
            accounts = Account.findAllByPerson(person)
        } else {
            accounts = Account.findAll([max: max, offset: offset, sort: 'id', order: order])
        }

        [person: person, accounts: accounts, people: Person.findAll()]


    }


    def removeAccount() {
        Account account = Account.findById(params.id);
        if (null == account) {
            render(status: 404, view: '/404', model: [message: '该帐户不存在'])
            return
        }


        account.delete(flush: true)

        render(contentType: 'text/json', text: "ok")
        return

    }

    def addPersonAccount() {
        Person person = Person.findById(params.personId)

        if (null == person) {
            render(status: 404, view: '/404', model: [message: '人员'])
            return
        }
        Account account = new Account(params)
        account.person = person;
        account.save(flush: true)

        redirect([controller: 'account', action: 'index', person: person])
    }

    def delete() {
        def id = params.id
        Account acount = Account.findById(id)
        if (null == acount) {
            render status: 404
            return
        }
        acount.delete(flush: true)
        render(contentType: "application/json") {
            [message: 'success']
        }

    }

    def reg() {
        if (!params.name) {
            return
        }

        Account account = new Account(params);
        Person person = new Person().save(flush: true);
        account.person = person
        if (account.validate()) {

            account.save(flush: true)
        }

        render view: 'reg', model: [account: account]
    }

    def login() {
        Account account = new Account();
        if (params.id) {
            account = Account.findById(params.id)
        }
        [account: account]
    }

    def logout(){
        session.invalidate()
        redirect(controller:'index',action: 'index')
    }


    def authenticat() {
        Account account = Account.findByNameAndPassword(params.name,params.password);
        if (account == null) {
            flash.message = '密码或帐户出错'
            redirect controller: 'account', action:'login'
            return

        }
        session['accountName'] = account.name
        session['accountShowName'] = account.showName
        redirect( controller: 'index',action: 'index')
    }





}
